package com.markerhub.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.*;
import com.markerhub.service.ManagerTeacherService;
import com.markerhub.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/manager-teacher")
public class ManagerTeacherController {
    @Autowired
    ManagerTeacherService teacherService;
@Autowired
    UserService userService;
    @RequiresAuthentication
    @GetMapping("/teacher/{id}")
    public Result selectById(@PathVariable(name = "id") Long id){
        ManagerTeacher teacher = teacherService.getById(id);
        Assert.notNull(teacher, "该teacher已被删除");

        return Result.succ(teacher);
    }

    @GetMapping("/all")
    public Result getAllTeacher() {
        List<ManagerTeacher> teachers = teacherService.list(); // 获取所有活动
        return Result.succ(teachers);
    }

    // 教师查询接口
    @RequiresAuthentication
    @GetMapping("/select")
    public Result getTeachers(
            @RequestParam(value = "id", required = false) Integer id,
            @RequestParam(value = "teacherName", required = false) String teacherName,
            @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {

        IPage teachers = teacherService.getTeachers(id, teacherName, currentPage, pageSize);
        return Result.succ(teachers);
    }




    @RequiresAuthentication
    @PostMapping("/teacher/edit")
    public Result edit(@Validated @RequestBody ManagerTeacher teacher) {
        // 如果传递的 loginId 不存在（即为 null 或 0），则新增一个 user 并设置角色为 student
        Long loginId = null;
        if (teacher.getLoginId() == null) {
            // 创建新用户
            User newUser = new User();
            newUser.setRole("teacher");
            newUser.setStatus(1);
            // 保存新用户到数据库
            userService.saveOrUpdate(newUser);
            // 获取新创建的用户的 ID
            loginId = newUser.getId();
            teacher.setLoginId(loginId);
        }


        teacherService.saveOrUpdate(teacher);

        return Result.succ("新增保存成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteTeacher(@PathVariable("id") Long id) {
        try {
            // 检查教师是否存在
            ManagerTeacher teacher = teacherService.getById(id);
            if (teacher == null) {
                return Result.fail("教师不存在");
            }
            // 检查教师是否有关联的班级或课程
            boolean hasRelations = teacherService.checkTeacherRelations(id);
            if (hasRelations) {
                return Result.fail("该教师还有关联的班级或课程，无法删除");
            }
            // 执行删除操作
            boolean success = teacherService.removeById(id);
            if (success) {
                return Result.succ("删除成功");
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除教师失败: ", e);
            return Result.fail("系统错误，删除失败");
        }
    }


}
